package com.example.icampusevent;

import com.example.icampusevent.jsonobjects.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class FriendListAdapter extends BaseAdapter {
	
	private Activity activity;
	private ArrayList<FriendEvent> friendList = null;
	private int mode;
	
	private ArrayList<CheckBox> boxes = new ArrayList<CheckBox>();
	
	// Friend Modes
	private final int ALL = 0;
	private final int NOTCHECKEDIN = 1;
	private final int CHECKEDIN = 2;
	private final int CHECKEDINUSER = 3;
	
	public FriendListAdapter(Activity _activity, int _mode, ArrayList<FriendEvent> _friendList) {
		activity = _activity;
		mode = _mode;
		friendList = _friendList;
	}

	public int getCount() {
		return friendList.size();
	}

	public Object getItem(int position) {
		return friendList.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		 View vi = convertView;
		 if(convertView==null) {
			 LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			 if(this.mode == NOTCHECKEDIN) {
				 vi = inflater.inflate(R.layout.invite_friends_row_layout, null);
			 }
			 else if(this.mode == CHECKEDIN) {
				 vi = inflater.inflate(R.layout.checkin_friend_row_layout, null);
			 }
			 else if(this.mode == CHECKEDINUSER){
				 vi = inflater.inflate(R.layout.add_friend_row_layout, null);
			 }
			 else {
				 vi = inflater.inflate(R.layout.view_friend_row_layout, null);
			 }
		 }
		 
		 final int p = position;
		 TextView friendName = (TextView)vi.findViewById(R.id.friend_name);
		 friendName.setText(friendList.get(position).getFirstname() + " " + friendList.get(position).getLastname());
		 if(this.mode == CHECKEDIN) {
			 TextView friendComment = (TextView)vi.findViewById(R.id.friend_comment);
			 friendComment.setText(friendList.get(position).getComment());
		 }
		 if(this.mode == CHECKEDINUSER) {
			 Button addFriendButton = (Button)vi.findViewById(R.id.add_friend_button);
			 addFriendButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					addFriend(p);
				}
			 });
		 }
		 if(this.mode == NOTCHECKEDIN) {
			 CheckBox checkBox = (CheckBox)vi.findViewById(R.id.select_friend_check_box);
			 boxes.add(checkBox);
		 }
		 if(this.mode == ALL) {
			 TextView eventTitle = (TextView)vi.findViewById(R.id.event_title);
			 eventTitle.setText(friendList.get(position).getTitle());
			 Button viewEventButton = (Button)vi.findViewById(R.id.view_event);
			 viewEventButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					viewEvent(p);
				}
			 });
		 }
    	 
		 return vi;
	}
	
	
	private void addFriend(int position) {
		FriendEvent friend = friendList.get(position);
		String friendId = friend.getUserid();
		String userId = ((EventDetailActivity)activity).getUserId();
		String url = "http://hamedaan.usc.edu:8080/team15/UserServlet?q=addfd&userid=" 
				+ userId + "&friendid=" + friendId;
		AddFriendTask task = new AddFriendTask();
		task.execute(url);
	}
	
	
	private class AddFriendTask extends AsyncTask<String, Integer, Reader> {
	    protected Reader doInBackground(String... url) {
	    	InputStream source = retrieveStream(url[0]);
	 		if(source == null) return null;
	 		
	 		Reader inputReader = new InputStreamReader(source);
	 		return inputReader;
	    }

	    protected void onPostExecute(Reader json) {
	 		Gson gson = new Gson();
			ReturnStatus rStatus = gson.fromJson(json, ReturnStatus.class);
			if(rStatus.getStatus().equals("success")) {
				toast("Success!");
			}
			else {
				toast("You are already friends.");
			}
	    }
	     
	    // Get data stream from server
	 	private InputStream retrieveStream(String url) {
	 		DefaultHttpClient client = new DefaultHttpClient();
	 		HttpGet request = new HttpGet(url);
	 		try {
	 			HttpResponse response = client.execute(request);
	 			final int status = response.getStatusLine().getStatusCode();
	 			if(status != HttpStatus.SC_OK) {
	 				toast("ERROR CODE: " + status + " for URL " + url);
	 				return null;
	 			}
	 			HttpEntity responseEntity = response.getEntity();
	 			return responseEntity.getContent();
	 		}
	 		catch(IOException e) {
	 			request.abort();
	 			toast("ERROR for " + url);
	 		}
	 		return null;
	 	}
	}
	
	
	private void viewEvent(int position) {
		long eventId = friendList.get(position).getEventid();
		String userId = ((FriendActivity)activity).getUserId();
		Intent intent = new Intent(activity, EventDetailActivity.class);
		intent.putExtra("USERID", userId);
		intent.putExtra("EVENTID", eventId);
		activity.startActivity(intent);
	}
	
	
	public ArrayList<CheckBox> getBoxes() {
		return this.boxes;
	}
	
	
	public void toast(String s) {
		CharSequence text = s;
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(activity, text, duration);
		toast.show();
	}

}
